package com.xin.bi.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.xin.bi.constant.AiConstant;
import com.xin.bi.exception.BusinessException;
import com.xin.bi.manager.AiManager;
import com.xin.bi.model.dto.chart.GenChartByAiRequest;
import com.xin.bi.model.entity.Chart;
import com.xin.bi.model.vo.BiResponse;
import com.xin.bi.service.ChartService;
import com.xin.bi.mapper.ChartMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author 鑫
 * @description 针对表【chart(图表信息表)】的数据库操作Service实现
 * @createDate 2023-07-11 11:37:13
 */
@Service
@Slf4j
public class ChartServiceImpl extends ServiceImpl<ChartMapper, Chart> implements ChartService {

    @Resource
    private ChartMapper chartMapper;

    @Resource
    private AiManager aiManager;

    /**
     * 同步操作 所有参数 插入图表
     * @param genChartByAiRequest
     * @param chartData
     * @param resAIData
     * @param userId
     * @return
     */
    @Override
    public BiResponse genChart(String genChartByAiRequest, String chartData, String resAIData, Long userId) {
        String[] split = resAIData.split("【【【【");
        if (split.length < 3) {
            throw new BusinessException("AI生成的图标数据有误");
        }
        String genChart = split[1];
        String genResult = split[2];
        Gson gson = new Gson();
        GenChartByAiRequest genChartByAiRequestData = gson.fromJson(genChartByAiRequest, GenChartByAiRequest.class);
        Chart chart = new Chart();
        chart.setGoal(genChartByAiRequestData.getGoal());
        chart.setName(genChartByAiRequestData.getName());
        chart.setChartData(chartData);
        chart.setChartType(genChartByAiRequestData.getChartType());
        chart.setGenChart(genChart);
        chart.setGenResult(genResult);
        chart.setUserId(userId);
        int insert = chartMapper.insert(chart);
        if (insert != 1) {
            throw new BusinessException("添加图表错误");
        }
        BiResponse biResponse = new BiResponse();
        BeanUtils.copyProperties(chart, biResponse);
        return biResponse;
    }

    /**
     * 先生成图表的部分信息
     *
     * @param genChartByAiRequest
     * @param chartData
     * @param userId
     * @return 新生成的图表id
     */
    @Override
    public Long preGenChart(String genChartByAiRequest, String chartData, Long userId) {
        Gson gson = new Gson();
        GenChartByAiRequest genChartByAiRequestData = gson.fromJson(genChartByAiRequest, GenChartByAiRequest.class);
        String goal = genChartByAiRequestData.getGoal();
        String name = genChartByAiRequestData.getName();
        String chartType = genChartByAiRequestData.getChartType();
        Chart chart = new Chart();
        chart.setGoal(goal);
        chart.setName(name);
        chart.setChartData(chartData);
        chart.setChartType(chartType);
        chart.setUserId(userId);
        int insert = chartMapper.insert(chart);
        if (insert != 1) {
            throw new BusinessException("预生成图表信息失败");
        }
        return chart.getId();
    }

    /**
     * 异步操作，更新预生成后的图表信息
     * @param chartId
     * @param sendAIMessage
     */
    @Override
    public void genChartAsync(Long chartId, String sendAIMessage) {
        // 修改成进行中
        Chart runningChart = new Chart();
        runningChart.setId(chartId);
        runningChart.setStatus("running");
        int i = chartMapper.updateById(runningChart);
        if (i != 1) {
            handleChartUpdateError(chartId, "更新图表执行中状态失败");
            return;
        }
        String resAIData = aiManager.doChat(AiConstant.BI_MODEL_ID, sendAIMessage);
        String[] split = resAIData.split("【【【【");
        if (split.length < 3) {
            throw new BusinessException("AI生成的图标数据有误");
        }
        String genChart = split[1];
        String genResult = split[2];
        Chart succeedChart = new Chart();
        succeedChart.setId(chartId);
        succeedChart.setStatus("succeed");
        succeedChart.setGenChart(genChart);
        succeedChart.setGenResult(genResult);
        int update = chartMapper.updateById(succeedChart);
        if (update != 1) {
            handleChartUpdateError(chartId, "更新图表成功状态失败");
            return;
        }
    }

    /**
     * 处理执行出错 修改execMessage
     * @param chartId
     * @param execMessage
     */
    public void handleChartUpdateError(Long chartId, String execMessage) {
        Chart chart = new Chart();
        chart.setId(chartId);
        chart.setExecMessage(execMessage);
        chart.setStatus("failed");
        int i = chartMapper.updateById(chart);
        if (i != 1) {
            log.error("更新图表失败状态失败" + chartId + "," + execMessage);
        }
    }

    /**
     * 拼接发给AI的数据
     * @param genChartByAiRequest
     * @param csvData
     * @return
     */
    @Override
    public String jointSendAiMessage(String genChartByAiRequest, String csvData) {
        Gson gson = new Gson();
        GenChartByAiRequest genChartByAiRequestData = gson.fromJson(genChartByAiRequest, GenChartByAiRequest.class);
        if (genChartByAiRequest == null) {
            throw new BusinessException("请求参数有误");
        }
        String goal = genChartByAiRequestData.getGoal();
        String name = genChartByAiRequestData.getName();
        String chartType = genChartByAiRequestData.getChartType();
        StringBuilder userGoal=new StringBuilder(goal);
        if(StringUtils.isNoneBlank(name)){
            userGoal.append("生成名字为").append(name);
        }
        if(StringUtils.isNoneBlank(chartType)){
            userGoal.append(chartType);
        }
        StringBuilder sendAIData = new StringBuilder();
        sendAIData.append("分析需求:").append("\n").append(userGoal).append("\n");
        sendAIData.append("原始数据:").append("\n").append(csvData);

        return sendAIData.toString();
    }

}




